package com.zsyh.jiujiu.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.zyh.toolslib.base.BaseActivity;
import com.example.zyh.toolslib.utils.EmptyUtil;
import com.example.zyh.toolslib.utils.SPUtils;
import com.example.zyh.toolslib.widget.TitleBar;
import com.google.gson.Gson;
import com.lwb.retrofit.RetrofitTask;
import com.zsyh.jiujiu.Api;
import com.zsyh.jiujiu.MainActivity;
import com.zsyh.jiujiu.R;
import com.zsyh.jiujiu.bean.MessageEvn;
import com.zsyh.jiujiu.bean.MoRenBean;
import com.zsyh.jiujiu.bean.MyGoodBean;
import com.zsyh.jiujiu.bean.OrderBuyBean;
import com.zsyh.jiujiu.bean.OrderListBean;
import com.zsyh.jiujiu.bean.OrderSucessBean;
import com.zsyh.jiujiu.dialog.ClallBackData;
import com.zsyh.jiujiu.dialog.OrderSucess;
import com.zsyh.jiujiu.net.MyObserver;
import com.zsyh.jiujiu.utils.BigDecimalUtil;
import com.zsyh.jiujiu.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.http.Query;

/**
 * @ProjectName: livvehelp
 * @Package: com.zsyh.lsb.ui
 * @ClassName:
 * @Description: java类作用描述
 * @Author: zsyh
 * @CreateDate: 2020/9/7 11:59
 * @UpdateUser: liangwanbo
 * @UpdateDate: 2020/9/7 11:59
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class SureOrderActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.adname)
    TextView adname;
    @BindView(R.id.adphone)
    TextView adphone;
    @BindView(R.id.adress)
    TextView adress;
    @BindView(R.id.rvlist)
    RecyclerView rvlist;
    @BindView(R.id.image_add)
    ImageView imageAdd;
    @BindView(R.id.readd)
    RelativeLayout readd;
    @BindView(R.id.huanrulogo)
    ImageView huanrulogo;
    @BindView(R.id.huanrugoodname)
    TextView huanrugoodname;
    @BindView(R.id.huan)
    ImageView huan;
    @BindView(R.id.fuhao)
    TextView fuhao;
    @BindView(R.id.jia)
    ImageView jia;
    @BindView(R.id.huanrunum)
    TextView huanrunum;
    @BindView(R.id.jian)
    ImageView jian;
    @BindView(R.id.huanruheji)
    TextView huanruheji;
    @BindView(R.id.remygood)
    RelativeLayout remygood;
    @BindView(R.id.totlemoney)
    TextView totlemoney;
    @BindView(R.id.tijiao)
    TextView tijiao;
    @BindView(R.id.hunchumoney)
    TextView hunchumoney;
    @BindView(R.id.moren)
    TextView moren;
    @BindView(R.id.redizhi)
    RelativeLayout redizhi;
    private BaseQuickAdapter<OrderBuyBean, BaseViewHolder> mAdapter;
    List<OrderBuyBean> list = new ArrayList<>();
    private String data;
    private double danjia;
    private double listtpric = 0.0;
    private double huanruprice = 0.0;
    private final static int REQUESTCODE = 1; // 返回的结果码
    private String dihiid;
    private String goodUserid;
    private String huanchugoodid;
    private String goodid="";
    private String carid="";
    private String shuliang="";

    @Override
    protected int initLayout() {
        return R.layout.activity_sure_order;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {
        data = getIntent().getStringExtra("data");
        Gson gson = new Gson();
        OrderListBean orderListBean = gson.fromJson(data, OrderListBean.class);
        for (int i = 0; i < orderListBean.getData().size(); i++) {
            list.add(orderListBean.getData().get(i));
            if(i==orderListBean.getData().size()-1){
                goodid=goodid+orderListBean.getData().get(i).getGoodid();
                carid=carid+orderListBean.getData().get(i).getCarid();

                shuliang=list.get(i).getNumber();
            }else{
                goodid=goodid+orderListBean.getData().get(i).getGoodid()+",";
                carid=carid+orderListBean.getData().get(i).getCarid()+",";

                shuliang=list.get(i).getNumber()+",";
            }

        }
        goodUserid=list.get(0).getGooduserid();
        for (int i = 0; i < list.size(); i++) {
            listtpric = listtpric + Double.valueOf(list.get(i).getGoodmoney()) * Integer.valueOf(list.get(i).getNumber());
        }
        totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");

        mAdapter = new BaseQuickAdapter<OrderBuyBean, BaseViewHolder>(R.layout.item_creart_order, list) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, OrderBuyBean item) {

                helper.setText(R.id.huanrugoodname, item.getGoodname());
                helper.setText(R.id.money, item.getGoodmoney());
                helper.setText(R.id.huanrunum, item.getNumber());
                helper.setText(R.id.huanruheji, "共" + item.getNumber() + "件商品  总价值：¥" + BigDecimalUtil.decimalTwo(Double.valueOf(item.getGoodmoney()) * Integer.valueOf(item.getNumber())) + "");
                Glide.with(thisActivity).load(item.getImageurl()).into(helper.<ImageView>getView(R.id.huanrulogo));
                helper.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       /* Bundle bundlehuan = new Bundle();
                        bundlehuan.putString("id", "id");
                        ActivityUtils.startActivity(bundlehuan, GoodinfoActivity.class);*/
                    }
                });
                helper.setOnClickListener(R.id.jia, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listtpric = 0.0;
                        shuliang="";
                        int nums = Integer.valueOf(helper.<TextView>getView(R.id.huanrunum).getText().toString()) + 1;
                        helper.<TextView>getView(R.id.huanrunum).setText(nums + "");
                        helper.setText(R.id.huanruheji, "共" + nums + "件商品  总价值：¥" + BigDecimalUtil.decimalTwo(Double.valueOf(item.getGoodmoney()) * nums) + "");
                        item.setNumber(nums + "");
                        list.set(helper.getPosition(), item);
                        for (int i = 0; i < list.size(); i++) {
                            listtpric = listtpric + Double.valueOf(list.get(i).getGoodmoney()) * Integer.valueOf(list.get(i).getNumber());
                            if(i==list.size()-1){
                                shuliang=list.get(i).getNumber();
                            }else{
                                shuliang=list.get(i).getNumber()+",";
                            }
                        }
                        totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");

                    }
                });

                helper.setOnClickListener(R.id.jian, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listtpric = 0.0;
                        shuliang="";
                        if (Integer.valueOf(helper.<TextView>getView(R.id.huanrunum).getText().toString()) == 1) {
                            helper.<TextView>getView(R.id.huanrunum).setText(1 + "");
                            item.setNumber(1 + "");
                            list.set(helper.getPosition(), item);
                            for (int i = 0; i < list.size(); i++) {
                                listtpric = listtpric + Double.valueOf(list.get(i).getGoodmoney()) * Integer.valueOf(list.get(i).getNumber());
                                if(i==list.size()-1){
                                    shuliang=list.get(i).getNumber();
                                }else{
                                    shuliang=list.get(i).getNumber()+",";
                                }
                            }
                            totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");
                        } else {
                            int nums = Integer.valueOf(helper.<TextView>getView(R.id.huanrunum).getText().toString()) - 1;
                            helper.<TextView>getView(R.id.huanrunum).setText(nums + "");
                            helper.setText(R.id.huanruheji, "共" + nums + "件商品  总价值：¥" + BigDecimalUtil.decimalTwo(Double.valueOf(item.getGoodmoney()) * nums) + "");
                            item.setNumber(nums + "");
                            list.set(helper.getPosition(), item);
                            for (int i = 0; i < list.size(); i++) {
                                listtpric = listtpric + Double.valueOf(list.get(i).getGoodmoney()) * Integer.valueOf(list.get(i).getNumber());
                                if(i==list.size()-1){
                                    shuliang=list.get(i).getNumber();
                                }else{
                                    shuliang=list.get(i).getNumber()+",";
                                }
                            }
                            totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");
                        }
                    }
                });

            }
        };
        rvlist.setLayoutManager(new LinearLayoutManager(thisActivity));
        rvlist.setAdapter(mAdapter);
    }

    @Override
    protected void initEvent() {


    }

    @Override
    protected void onResume() {
        super.onResume();
        morenad((String) SPUtils.get(thisActivity, "userid", ""));
    }

    @OnClick({R.id.readd, R.id.jia, R.id.jian, R.id.tijiao, R.id.redizhi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.redizhi:
                Intent intent = new Intent(this, AdressManger.class);
                startActivityForResult(intent, REQUESTCODE);
                break;
            case R.id.readd:
                ActivityUtils.startActivity(MyGoodActivity.class);
                break;
            case R.id.jia:
                int num = Integer.valueOf(huanrunum.getText().toString()) + 1;
                huanrunum.setText(num + "");
                huanruheji.setText("共" + num + "件商品  总价值：¥" + BigDecimalUtil.decimalTwo(danjia * num) + "");
                huanruprice = danjia * num;
                totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");
                break;
            case R.id.jian:
                if (Integer.valueOf(huanrunum.getText().toString()) == 1) {
                    huanrunum.setText(1 + "");
                    huanruheji.setText("共" + 1 + "件商品  总价值：¥" + BigDecimalUtil.decimalTwo(danjia * 1) + "");
                    huanruprice = danjia * 1;
                    totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");
                } else {
                    int nums = Integer.valueOf(huanrunum.getText().toString()) - 1;
                    huanrunum.setText(nums + "");
                    huanruheji.setText("共" + nums + "件商品  总价值：¥" + BigDecimalUtil.decimalTwo(danjia * nums) + "");
                    huanruprice = danjia * nums;
                    totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");
                }
                break;
            case R.id.tijiao:
                Log.e("canshu","goodUserid="+goodUserid+"huanchugoodid=+"+huanchugoodid+"goodid="+goodid+"shuliang="+shuliang+"carid="+carid+"huanru="+huanrunum.getText().toString());
                if(EmptyUtil.isEmpty(huanchugoodid)){
                    ToastUtils.showShort(thisActivity,"请添加换出商品");
                    return;
                }
                creatorder((String) SPUtils.get(thisActivity, "userid", ""),
                        goodUserid,
                        adname.getText().toString(),
                        adphone.getText().toString(),
                        adress.getText().toString(),
                        huanchugoodid,
                        huanrunum.getText().toString(),
                        goodid,
                        shuliang,
                        carid
                        );
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(MessageEvn messageInfo) {
        if (messageInfo.getMessage().equals("add")) {
            readd.setVisibility(View.GONE);
            remygood.setVisibility(View.VISIBLE);
            Gson gson = new Gson();
            MyGoodBean.DataBean bean = gson.fromJson(messageInfo.getCode(), MyGoodBean.DataBean.class);
            //huanrulogo
            String[] split = bean.getGoodsPic().split("\\|");
            Glide.with(thisActivity).load(split[0]).into(huanrulogo);
            huanrugoodname.setText(bean.getGoodsTitle());
            hunchumoney.setText(bean.getGoodsPrice() + "");
            danjia = bean.getGoodsPrice();
            huanruheji.setText("共" + 1 + "件商品  总价值：¥" + BigDecimalUtil.decimalTwo(Double.valueOf(bean.getGoodsPrice()) * 1) + "");
            huanruprice = Double.valueOf(bean.getGoodsPrice()) * 1;
            totlemoney.setText(BigDecimalUtil.decimalTwo(listtpric + huanruprice) + "");
            huanchugoodid=bean.getId();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }


    /**
     * 获取默认地址
     */
    public void morenad(String userid) {
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .getDefaultAddress(userid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, false) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("morendizhi", JsonStr + "");
                        Gson gson = new Gson();
                        MoRenBean myAdressBean = gson.fromJson(JsonStr, MoRenBean.class);
                        adname.setText(myAdressBean.getData().getUserName());
                        adphone.setText(myAdressBean.getData().getUserPhone());
                        adress.setText(myAdressBean.getData().getAddressProvname() + myAdressBean.getData().getAddressCityname() + myAdressBean.getData().getAddressDistname() + myAdressBean.getData().getAddressDesc());
                        if (myAdressBean.getData().getIsDefault().equals("1")) {
                            moren.setVisibility(View.VISIBLE);
                        } else {
                            moren.setVisibility(View.GONE);
                        }
                        dihiid = myAdressBean.getData().getId();

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == REQUESTCODE) {
                String name = data.getStringExtra("name");
                String phone = data.getStringExtra("phone");
                String adressd = data.getStringExtra("adress");
                String id = data.getStringExtra("id");
                String ismoren = data.getStringExtra("ismoren");
                dihiid = id;
                adname.setText(name);
                adphone.setText(phone);
                adress.setText(adressd);
                if (ismoren.equals("1")) {
                    moren.setVisibility(View.VISIBLE);
                } else {
                    moren.setVisibility(View.GONE);
                }


            }
        }
    }

    /**
     * 订单
     */
    public void creatorder(String userId,
                           String otherUserId,
                           String username,
                           String phone,
                           String address,
                           String goodsId,
                           String num,
                           String otherGoodsIds,
                           String otherNums,
                           String carIds) {
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .saveCarOrder(userId,
                        otherUserId,
                        username,
                        phone,
                        address,
                        goodsId,
                        num,
                        otherGoodsIds,
                        otherNums,
                        carIds)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, false) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("order", JsonStr + "");
                        Gson gson = new Gson();
                        OrderSucessBean orderSucessBean=gson.fromJson(JsonStr,OrderSucessBean.class);
                        if(orderSucessBean.getCode()==0){
                            OrderSucess orderSucess=new OrderSucess();
                            orderSucess.setSelectAddresFinish(new ClallBackData() {
                                @Override
                                public void getData(String data, String name, String number) {
                                    if(data.equals("1")){
                                        EventBus.getDefault().post(new MessageEvn("home", "home"));
                                        Intent mainIntent = new Intent(thisActivity, MainActivity.class);
                                        mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                        SPUtils.putString(mContext, "fragment_pos", "2");
                                        startActivity(mainIntent);
                                    }else{

                                        Bundle bundleall = new Bundle();
                                        bundleall.putString("name", "0");
                                        ActivityUtils.startActivity(bundleall, MyOrderActivity.class);

                                    }
                                    thisActivity.finish();
                                }
                            });
                            orderSucess.show(getSupportFragmentManager(),"");
                        }


                    }
                });
    }

}
